<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-input
          v-model="query.taskName"
          clearable
          size="small"
          placeholder="请输入任务名称"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.status"
          filterable
          clearable
          size="small"
          placeholder="请选择转换状态"
          class="filter-item"
          style="width: 200px"
        >
          <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!-- 功能按钮 -->
      <crudOperation :permission="permission" />
    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      style="width: 100%;"
      :data="crud.data"
      @filter-change="crud.handleFilterChange"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column v-if="columns.visible('taskName')" :show-overflow-tooltip="true" label="任务名称" prop="taskName" min-width="150" />
      <el-table-column v-if="columns.visible('convertType')" :show-overflow-tooltip="true" label="迁移类型" prop="convertType" min-width="150" />
      <el-table-column v-if="columns.visible('status')" label="转换状态" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 'TODO'" type="info">待转换</el-tag>
          <el-tag v-if="scope.row.status === 'PROCESSING'">转换中</el-tag>
          <el-tag v-if="scope.row.status === 'FINISH'" type="success">完成</el-tag>
          <el-tag v-if="scope.row.status === 'FAIL'" type="danger">失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('todoNum')" prop="todoNum" label="转换进度" min-width="280">
        <template slot-scope="scope">
          <el-tag type="info">总数：{{ scope.row.todoNum }}</el-tag>
          <el-tag type="success" style="margin: 0px 5px">转换成功: {{ scope.row.successNum }}</el-tag>
          <el-tag type="danger">转换失败: {{ scope.row.failNum }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('convertStartTs')" prop="convertStartTs" label="开始时间" min-width="150">
        <template slot-scope="scope">
          <div>
            <i class="el-icon-time" />
            <span style="margin-left: 5px">{{ scope.row.convertStartTs }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('convertEndTs')" prop="convertEndTs" label="结束时间" min-width="150">
        <template slot-scope="scope">
          <div>
            <i class="el-icon-time" />
            <span style="margin-left: 5px">{{ scope.row.convertEndTs }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('upUserName')" prop="upUserName" label="更新人" />
      <el-table-column v-if="columns.visible('upTs')" prop="upTs" label="更新时间" min-width="150" />
      <!-- <el-table-column v-if="columns.visible('crtTs')" :show-overflow-tooltip="true" label="创建时间" prop="crtTs" /> -->
      <el-table-column
        v-if="columns.visible('zh')"
        label="转换清单"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleClick(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="下载" min-width="150">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="downloadZipTemplate(scope.row)">源文件</el-button>
          <el-button type="text" size="small" @click="resultDocument(scope.row)">结果文件</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
    <!--脚本迁移-->
    <el-dialog
      v-if="crud.status.cu === 1"
      :visible.sync="crud.status.cu === 1"
      append-to-body
      :close-on-click-modal="false"
      title="脚本迁移"
      top="5vh"
      width="1200px"
      @close="crud.cancelCU()"
    >
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="130px">
        <el-row>
          <el-col :span="22">
            <el-steps :active="active" finish-status="success" simple>
              <el-step title="确认清单" />
              <el-step title="转换结果" />
              <el-step title="验证结果" />
              <el-step title="确认成果" />
            </el-steps>
          </el-col>
          <el-col :span="2">
            <div class="grid-content bg-purple-light">
              <el-button icon="el-icon-question" class="assist" @click="helpFormVisible = true">帮助</el-button>
            </div>
          </el-col>
        </el-row>
        <div v-if="active === 0">
          <create-task v-if="active === 0" ref="createTask" v-model="form" :crud="crud" />
          <div slot="footer" class="dialog-footer" style="width:100%;text-align: center;margin-top: 10px">
            <el-button @click="crud.cancelCU()">关 闭</el-button>
            <el-button type="primary" @click="toConvert">下一步(转换)</el-button>
          </div>
        </div>
        <div v-if="active === 1">
          <convert-result v-if="active === 1" :convert-task-pk-id="convertTaskId" :task-name="form.taskName" />
          <div class="dialog-footer" style="width:100%;text-align: center;margin-top: 10px">
            <el-button type="primary" @click="back">上一步</el-button>
            <el-button type="primary" @click="toScriptVerify">下一步(脚本验证)</el-button>
          </div>
        </div>
        <div v-if="active === 2">
          <script-test-result :convert-task-pk-id="convertTaskId" />
          <div class="dialog-footer" style="width:100%;text-align: center;margin-top: 40px">
            <el-button type="primary" @click="back">上一步</el-button>
            <el-button type="primary" @click="active ++">下一步</el-button>
          </div>
        </div>
        <div v-if="active === 3">
          <script-final-result :convert-task-pk-id="convertTaskId" />
          <div class="dialog-footer" style="width:100%;text-align: center;margin-top: 40px">
            <el-button type="primary" @click="back">上一步</el-button>
            <el-button type="primary" @click="crud.cancelCU()">关闭</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>
    <!-- 查看帮助文档 -->
    <el-dialog title="帮助" :visible.sync="helpFormVisible" width="1200px">
      <div>
        <script-convert-helper />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/expand/script/transfer/CRUD.operation'
import pagination from '@crud/Pagination'
import createTask from './components/createTask/create-task'
import convertResult from './components/convertResult/convert-result'
import scriptConvertHelper from './components/helper/helper'
import scriptConvertTaskApi from '@/api/script/transfer/script-convert-task'
import scriptTestResult from './components/verifyResult'
import scriptFinalResult from './components/finalResult'
import { downloadFile } from '@/utils/index'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '脚本转换任务', url: '/api/script/convert/task', crudMethod: { ...scriptConvertTaskApi }})
const defaultForm = {
  pkId: null,
  scriptImportType: 'FILE',
  convertType: '',
  taskName: null,
  isHiddenUploadFile: false,
  isHiddenValu: false,
  isHiddenImportType: false,
  proceduresList: [],
  fileList: [],
  tmpFileList: [],
  sourceConnCode: null,
  targetConnCode: null,
  dbName: null,
  status: 'TODO',
  verifyStatus: 'TODO',
  verifyTotalNum: 0,
  verifySuccessNum: 0
}
export default {
  name: 'ScriptConvertTask',
  components: {
    crudOperation,
    rrOperation,
    pagination,
    convertResult,
    createTask,
    scriptConvertHelper,
    scriptTestResult,
    scriptFinalResult
  },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    var validateTaskName = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback(new Error('请输入任务名称'))
      } else {
        scriptConvertTaskApi.findListByPage(value).then(rsp => {
          let isExistFlag = false
          if (rsp.total > 0) {
            rsp.content.forEach(item => {
              if (value === item.taskName) {
                isExistFlag = true
              }
            })
          }
          if (isExistFlag) {
            callback(new Error('任务名称已存在！'))
          } else {
            callback()
          }
        })
      }
    }
    return {
      convertTaskId: null,
      forbidden: false,
      active: 0,
      projectList: [],
      helpFormVisible: false,
      taskName: null,
      permission: {
        add: ['admin', 'script:add'],
        del: ['admin', 'script:del']
      },
      statusOptions: [
        { key: 'TODO', label: '待转换' },
        { key: 'PROCESSING', label: '转换中' },
        { key: 'FINISH', label: '完成' },
        { key: 'FAIL', label: '失败' }
      ],
      rules: {
        taskName: [
          { required: true, validator: validateTaskName, trigger: 'blur' }
        ],
        scriptImportType: [
          { required: true, message: '请选择脚本导入方式', trigger: 'change' }
        ],
        convertType: [
          { required: true, message: '请选择转换类型', trigger: 'change' }
        ],
        dbName: [
          { required: true, message: '请选择数据库名', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
  },
  created() {
    this.crud.resetQuery(false)
  },
  methods: {
    [CRUD.HOOK.beforeToAdd](crud) {
      this.active = 0
      crud.resetForm()
    },
    [CRUD.HOOK.afterAddCancel](crud) {
      crud.refresh()
    },
    // 源文件下载
    downloadZipTemplate(row) {
      crud.downloadLoading = true
      scriptConvertTaskApi.downloadFile(row.pkId).then(result => {
        downloadFile(result, row.taskName + '-源文件清单', 'zip')
        crud.downloadLoading = false
      }).catch(() => {
        this.$notify({ title: '失败', message: '下载源文件失败！', type: 'error' })
        crud.downloadLoading = false
      })
    },
    // 结果文件下载
    resultDocument(row) {
      crud.downloadLoading = true
      scriptConvertTaskApi.convertFile(row.pkId).then(result => {
        downloadFile(result, row.taskName + '-结果文件清单', 'zip')
        crud.downloadLoading = false
      }).catch(() => {
        this.$notify({ title: '失败', message: '下载结果文件失败！', type: 'error' })
        crud.downloadLoading = false
      })
    },
    async toConvert() {
      if (this.crud.form.status === 'TODO') {
        this.$refs['form'].validate((valid) => {
          if (this.crud.form.sourceConnCode === '' || this.crud.form.targetConnCode === '') {
            this.$confirm(`请确认是否不配置服务器?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              if (valid && this.checkHasScriptList()) {
                const dataForm = JSON.parse(JSON.stringify(this.crud.form))
                this.formatFileList(dataForm)
                scriptConvertTaskApi.add(dataForm).then(data => {
                  this.convertTaskId = data
                  this.crud.form.isHiddenValu = true
                  this.crud.form.isHiddenUploadFile = true
                  this.crud.form.status = 'PROCESSING'
                  this.active++
                })
              }
            }).catch(() => {
            })
          } else {
            if (valid && this.checkHasScriptList()) {
              const dataForm = JSON.parse(JSON.stringify(this.crud.form))
              this.formatFileList(dataForm)
              scriptConvertTaskApi.add(dataForm).then(data => {
                this.convertTaskId = data
                this.crud.form.isHiddenValu = true
                this.crud.form.isHiddenUploadFile = true
                this.crud.form.status = 'PROCESSING'
                this.active++
              })
            }
          }
        })
      } else {
        this.active++
      }
    },
    async toScriptVerify() {
      scriptConvertTaskApi.queryById(this.convertTaskId).then(res => {
        if (res.status !== 'FINISH') {
          this.$notify({ title: '告警', message: '请等待脚本转换完成后再进行验证！', type: 'warning' })
        } else if (res.verifyStatus === 'TODO') {
          scriptConvertTaskApi.scriptVerify(this.convertTaskId).then(data => {
            this.active++
          })
        } else {
          this.active++
        }
      })
    },
    formatFileList(dataForm) {
      const fileList = []
      dataForm.fileList.forEach(item => {
        fileList.push(item.filePath)
      })
      dataForm.fileList = fileList
    },
    checkHasScriptList() {
      if (this.crud.form.fileList.length < 1 && this.crud.form.proceduresList.length < 1) {
        this.$notify({ title: '告警', message: '请选择上传或选择要转换的脚本！', type: 'warning' })
        return false
      }
      return true
    },
    back() {
      this.active--
      this.form.isHiddenValu = true
      this.form.isHiddenUploadFile = true
    },
    next() {
      this.active++
    },
    // 查看转换清单详情
    handleClick(data) {
      this.convertTaskId = data.pkId
      this.form.pkId = data.pkId
      this.form.isHiddenValu = false
      this.form.isHiddenUploadFile = false
      this.form.isHiddenImportType = true
      this.form.taskName = data.taskName
      this.form.convertType = data.convertType
      this.form.sourceConnCode = data.sourceConnCode
      this.form.targetConnCode = data.targetConnCode
      this.form.projectPkId = data.projectPkId
      this.active = 1
      this.form.status = data.status
      if (data.status === 'TODO') {
        this.active = 0
      }
      this.crud.status.edit = 1
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.assist {
  min-height: 46px;
  color: #fff;
  background-color: #ff4949;
  border-color: #ff4949;
}
</style>
